#include "spu.h"

int cnt;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  //定义互斥量并初始化

int main()
{
    pid_t pid, pid2;
    printf("I am the main, %d\n",getpid());

    pid = fork();
    if(pid < 0)
    {
        printf("子线程创建失败\n");
        return 0;
    }

    if(pid > 0)
    {
        while(1)
        {
            pthread_mutex_lock(&mutex);
            cnt++;
            printf("大家好，我是主线程，我的id是 %d, cnt = %d\n",getpid(), cnt);
            pthread_mutex_unlock(&mutex);
            sleep(1);
        }
    }else if(pid == 0)
    {
        pid2 = fork();
        if(pid2 > 0)
        {
            while(1)
            {
                pthread_mutex_lock(&mutex);
                cnt++;
                printf("大家好，我是子线程中的主线程，我的id是 %d, cnt = %d\n",getpid(), cnt);
                pthread_mutex_unlock(&mutex);
                sleep(1);
            }
        }else if(pid == 0)
        {

            while(1)
            {
                pthread_mutex_lock(&mutex);
                ++cnt;
                printf("大家好，我是子线程的子线程，我的id是 %d, cnt = %d\n",getpid(), cnt);
                pthread_mutex_unlock(&mutex);
                sleep(1);
            }
        }
    }


    return 0;
}
